# -*- coding: utf-8 -*-
# @Time    : 2022/6/30 18:01
# @Author  : AUGUS
# @Email   : augus@jilin.com
# @File    : verifyUtil.py
# @Software: PyCharm
import os
import random
import string
from PIL import Image, ImageFont, ImageDraw, ImageFilter


# from random import random
from django_redis import get_redis_connection

from config.dbs.redis_dev import LOGIN_KEY_TEMPLATE


class ImageVerify:
    def __init__(self, width=140, height=40, length=4, size=28):
        """
        初始化
        :param width: 图片的X轴，宽度
        :param height: 图片的Y轴，高度
        :param length:  字符的个数，长度
        :param size:  字符的大小
        """
        self.width = width
        self.height = height
        self.length = length
        self.size = size

    def random_str(self):
        """
        随机生成指定长度的字符串
        :return: 生成的随机字符串
        """
        source = string.ascii_letters + string.digits
        return ''.join(random.sample(source, self.length))

    def random_color(self, start=0, end=255):
        """
        随即生成颜色，一张有颜色的栅格图是三维数据
        [
        [(1,2,3),(1,2,3)],
        [(1,2,3),(1,2,3)],
        ]
        :param start: 颜色范围的最小值，起始值
        :param end:  颜色范围的最大值，结束值
        :return:tuple (r,g,b) 0-255
        """
        res = [random.randint(start, end) for i in range(3)]
        return tuple(res)

    def random_lines(self, draw):
        """
        绘制干扰线
        :param draw对象 画笔
        :return:
        """
        for i in range(self.length):
            lines = [(random.randint(0, self.width), random.randint(0, self.height)) for i in range(2)]
            draw.line(lines, fill=self.random_color(64, 200))

    def random_points(self, draw, rate):
        """
        绘制干扰点
        :param draw: draw 对象 画笔
        :param rate: 频率 干扰点出现的频率
        :return:
        """
        for x in range(self.width):
            for y in range(self.height):
                if random.randint(1, 100) <= rate:
                    draw.point((x, y), fill=self.random_color(64, 200))

    def verify_code(self):
        """
        生成验证码图片
        :return: 图片以及验证码的正确答案
        """
        # 创建Image对象， 创建画布
        image = Image.new('RGB', (self.width, self.height), (255, 255, 255))
        # 创建Font对象 字体
        file = os.path.dirname(os.path.abspath(__file__))
        font = ImageFont.truetype(f'{file}/HYYakuHei-85W.ttf', self.size)

        # 创建Draw对象 画笔， 绘制图形，点，线
        draw = ImageDraw.Draw(image)
        # 绘制干扰线和干扰点
        self.random_lines(draw)
        self.random_points(draw, 15)
        # 调用随机生成字符方法，验证码值
        code = self.random_str()
        # 使用画笔将Font类型的字体对应的字符内容和颜色控制
        for i in range(self.length):
            draw.text((35*i+5, 3), code[i], font=font, fill=self.random_color(32, 127))
        # 模糊滤镜
        image = image.filter(ImageFilter.BLUR)
        return image, code


def jwt_token(token, user=None, request=None):
    """
    自定义登录成功后的响应函数，登陆后的数据处理函数。
    执行这个函数，账号和密码肯定是正确有效的了，手动校验验证码即可
    :param token: 令牌
    :param user: 登陆的用户
    :param request: 请求对象
    :return: 登录接口相应的内容，token
    """
    param = request.data
    uuid = param.get('uuid')
    verify = param.get('verify')

    if not uuid or not verify:
        return {'msg': '请输入验证码'}

    # 得到redis保存的该客户端的验证码答案与它传入过来的结果进行判断
    cache = get_redis_connection(alias='verify_code')
    redis_verify = cache.get(LOGIN_KEY_TEMPLATE % uuid)
    cache.delete(LOGIN_KEY_TEMPLATE % uuid)
    if not redis_verify:
        return{'msg': '验证码过期'}

    if redis_verify.upper() != verify.upper():
        return {'msg': '验证码错误'}

    return {
        'token': token,
        'id': user.id,
        'username': user.username,
        'avatar': user.userdetail.avatar if hasattr(user, 'userdetail') else None,
    }


if __name__ == '__main__':
    imgVerify = ImageVerify()
    img, code = imgVerify.verify_code()  # 生成验证码图片方法
    with open('test.png', 'wb') as fp:
        img.save(fp)
    print(code)
